//
//  FKLiveVC.m
//  LiveDemo1
//
//  Created by xmc06 on 16/10/13.
//  Copyright © 2016年 zmosa. All rights reserved.
//

#import "FKLiveVC.h"
#import "FKLiveItem.h"
#import "FKCreatorItem.h"
#import <IJKMediaFramework/IJKMediaFramework.h>
#import <UIImageView+WebCache.h>

@interface FKLiveVC ()
@property (nonatomic, weak) UIImageView *placeholderView;
@property (nonatomic, strong) IJKFFMoviePlayerController *player;
@end

@implementation FKLiveVC

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setupSubviews];
}

- (void)setupSubviews
{
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIImageView *placeholderView = [[UIImageView alloc] init];
    [self.view addSubview:placeholderView];
    self.placeholderView = placeholderView;
    placeholderView.frame = self.view.bounds;
    // 设置直播占位图片
    NSURL *imageURL = [NSURL URLWithString:[NSString stringWithFormat:@"http://img.meelive.cn/%@", self.live.creator.portrait]];
    [self.placeholderView sd_setImageWithURL:imageURL];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:backBtn];
    backBtn.frame = CGRectMake(0, 64, 80, 40);
    [backBtn setTitle:@"返回" forState:UIControlStateNormal];
    backBtn.backgroundColor = [UIColor lightGrayColor];
    [backBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    
    // 拉流地址
    NSURL *streamURL = [NSURL URLWithString:self.live.stream_addr];
    // 创建IJKFFMoviePlayerController: 专门用来直播，传入拉流地址就好了
    IJKFFMoviePlayerController *playerVC = [[IJKFFMoviePlayerController alloc] initWithContentURL:streamURL withOptions:nil];
    // 准备播放
    [playerVC prepareToPlay];
    // 强引用，防止被销毁
    self.player = playerVC;
    playerVC.view.frame = self.view.bounds;
    [self.view insertSubview:playerVC.view atIndex:1];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    // 界面小时，一定要记得停止播放
    [self.player pause];
    [self.player stop];
    [self.player shutdown];
}

/**
 *  返回
 */
- (void)back
{
    [self dismissViewControllerAnimated:true completion:nil];
}

@end
